import { defineComponent, watch, ref } from 'vue'
import { ElUpload, ElButton } from 'element-plus'
import 'element-plus/dist/index.css';

import './style.scss'
import myMeta from './meta'

export const meta = myMeta
/**
 * 支持配置：
 * 内容限制格式，valid
 * 字数限制，textRange
 * 引导提示文案，placeholder
 */
export default defineComponent({
  name: 'UploadModule',
  props: {
    type: {
      type: String,
      default: ''
    },
    field: {
      type: String,
      default: ''
    },
    value: {
      type: [Array, String],
      default: () => []
    },
    formatRange: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请填写'
    },
    textRange: {
      type: Object,
      default: () => {
        return {
          max: {
            placeholder: '500',
            value: 500
          },
          min: {
            placeholder: '0',
            value: 0
          }
        }
      }
    },
    valid: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  emits: ['blur', 'focus', 'input', 'change'],
  setup(props, { emit }) {
    const focusFlag = ref(false)
    const initial = props.textRange.max.value - props.value.length
    const getLeftTextNumber = ref(initial)
    const fileList = ref([])

    // watch(
    //   () => props.value,
    //   (val) => {
    //     if (val) {
    //       let arr = []
    //       if (Array.isArray(props.value) && props.value.length) {
    //         props.value.forEach((item) => {
    //           arr.push(item.localPath)
    //         })
    //       } else if (props.value && typeof props.value === 'string') {
    //         arr = props.value.split(',')
    //       }
    //       fileList.value = arr
    //     }
    //   }
    // )
  

    const beforeUpload = (file) => {
      // const isJPG = file.type === 'image/jpeg'
      // const isPNG = file.type === 'image/png'
      // const isJPEG = file.type === 'image/jpeg'
      // const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 20
      // if (!isJPG) {
      //   return false
      // }
      // if (!isPNG) {
      //   return false
      // }
      // if (!isJPEG) {
      //   return false
      // }
      // if (!isGIF) {
      //   return false
      // }
      if (!isLt2M) {
        window.$ui.msg('上传文件大小不能超过 20MB!')
        return false
      }
      return true
    }

    const handleRemove = (uploadFile, uploadFiles) => {
      console.log(uploadFile)
      uploadFile?.response?.fileInfos?.forEach((item) => {
        fileList.value = fileList.value.filter((file) => file.filename !== item.filename)
      })
      // emit('change', {
      //   key: props.field,
      //   value: uploadFiles.map((item) => item.localPath)
      // })
    }
    
    const handlePictureCardPreview = (uploadFile) => {
      // dialogImageUrl.value = uploadFile.localPath
      // dialogVisible.value = true
      console.log(uploadFile)
    }
    const onChange = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
      const key = props.field
      uploadFile?.data?.forEach((item) => {
        fileList.value.push({
          ...item
        })
      })
      // const maxLength = get(props, 'textRange.max.value')
      // if (
      //   get(props, 'valid') === 'n' &&
      //   maxLength &&
      //   e.target.value.toString().length > maxLength
      // ) {
      //   e.target.value = e.target.value.slice(0, props.textRange.max.value)
      // }
      // if (['m', 'idcard', 'e', 'licensePlate'].includes(props.valid)) {
      //   e.target.value = e.target.value.replace(/\s+/g, '')
      // }

      emit('change', {
        key,
        value: fileList.value // .map((item) => item.localPath)
      })
    }
// 'application/pdf', 'image/*', 'video/*', 'audio/*', 'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    const getFileName = (filePath) => {
      if (typeof filePath !== 'string') {
        return null;
      }
      const parts = filePath.split(/[/\\]/);
      return parts[parts.length - 1];
    }

    let uploadData = {
      unZip: true,
      frameNum: 1,
      userId: window.$app.user.userId,
      priority: '7',
      sourceDel: '0',
      ttlTimes: '7',
      timePoint: '00:00:05'
    }
    let uploadHeaders = {
      branchCode: window.$app.user.branchCode || 'twpaas',
      'X-Client-Language': 'zh_CN',
      'Access-Token': window.$app.user.token,
      'X-User-Account': window.$app.user.userId
    }

    return {
      props,
      focusFlag,
      getLeftTextNumber,
      onChange,
      handlePictureCardPreview, 
      handleRemove,
      beforeUpload,
      uploadData,
      uploadHeaders,
      fileList,
      getFileName
    }
  },
  render() {
    const { beforeUpload, onChange, handlePictureCardPreview, handleRemove, props, uploadData, uploadHeaders, fileList, readonly, getFileName } = this
    
    return (
      <div>
        {readonly&&(<div class="uploadfile-list">
        {fileList.map((item, index) => {
            return (
              <div
                key={index}
                class={['uploadfile-item']}
              >
                <div style="position: relative">
                  <div
                    class={[
                      'choice-item'
                    ]}
                    onClick={($event) => {
                      handlePictureCardPreview(item, $event)
                    }}
                  >
                    {item && getFileName(item)}
                  </div>
                </div>
              </div>
            )
          })}
        </div>)}
        <ElUpload
          accept={['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'].join(',')}
          drag
          show-file-list={!readonly}
          action={window.$app.fileUploadUrl}
          on-preview={handlePictureCardPreview}
          on-success={onChange}
          before-upload={beforeUpload}
          on-remove={handleRemove}
          disabled={readonly}
          headers={uploadHeaders}
        >
          <ElButton type="primary" disabled={readonly}>点击上传</ElButton>
        </ElUpload>
      </div>
    )
  }
})
